package com.zhangye.test.service;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.collections.MapUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhangye.test.mapper.WechatOrderInfoMapper;
import com.zhangye.test.model.PayList;
import com.zhangye.test.model.WechatOrderInfo;
import com.zhangye.test.util.Arith;
import com.zhangye.test.util.HttpTookit;
import com.zhangye.test.util.OrderInfoUtil2_0;
import com.zhangye.test.util.Sign;
import com.zhangye.test.util.StringUtils;
import com.zhangye.test.util.XMLPojoMapConverter;


@Service
public class WechatOrderInfoService {
	@Autowired
	private WechatOrderInfoMapper wechatOrderInfoMapper;

	@Autowired
	private PayListService payListService;
	
	
	public Map<String, Object> orderNew(Map<String, Object> param, Long mId) throws ParseException, DocumentException{
		
		WechatOrderInfo who;
		String result = "";
		String sign = "";
		String prepayId = "";
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> results = new HashMap<String, Object>();
		SortedMap<Object,Object> param1 = new TreeMap<Object,Object>();
		Map<String, Object> prepay_id = null;
		Map<String, Object> return_code = null;
		Map<String, Object> result_code = null;
		String ip = (String) param.get("ip");
		double pay_amount = Double.parseDouble((String) param.get("pay_amount"));
		int total = Arith.convertsToInt(Arith.mul(pay_amount, 100));
		int payId = (int) param.get("id");
		String body = "AR在线";
		if (param.get("body")!=null&&!param.get("body").equals("")) {
			body = (String) param.get("body");
		}
		
		String out_trade_no = OrderInfoUtil2_0.getOutTradeNo();
		results.put("status", "1");
		
		//判断金额是否正确
		String where = " and deleteLogo = '0' ";
		where += " and pay_sum = " + pay_amount + " and id = " + payId;
		List<PayList> list = payListService.selectByWhere(where);
		if (list.size() > 0) {
			SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
			parameters.put("appid", "wx5e5830f49c6d3d8b"); //微信开放平台审核通过的应用APPID
			parameters.put("mch_id", "1514526381"); 	   //微信支付分配的商户号
			parameters.put("nonce_str", StringUtils.generatorNumber(15)); //随机字符串，不长于32位
			parameters.put("body", body); 	   			   //商品描述
			parameters.put("out_trade_no", out_trade_no);  //系统内部的订单号,
			parameters.put("total_fee", total);			   //订单总金额（分）
			parameters.put("spbill_create_ip", ip); 	   //终端IP
			parameters.put("notify_url", "http://ar.zhyell.com/api/weChat/async"); //接收微信支付异步通知回调地址
			parameters.put("trade_type", "APP"); 		   //支付类型
			
			String mySign = Sign.createSign("UTF-8",parameters);  
			parameters.put("sign", mySign);
			
			//转换xml
			byte[] aa = XMLPojoMapConverter.callMapToXML(parameters);
			String data = new String(aa);
			
			//调用微信API生成预支付交易单
			String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
			result = HttpTookit.httpsRequest(url, "POST", data);
			
			//xml转换map
			map = XMLPojoMapConverter.xml2map(result); 
			if(MapUtils.isNotEmpty(map))
			{
				return_code = (Map<String, Object>) map.get("return_code");
				result_code = (Map<String, Object>) map.get("result_code");
				if(return_code.get("return_code").equals("SUCCESS") && result_code.get("result_code").equals("SUCCESS"))
				{
					prepay_id = (Map<String, Object>) map.get("prepay_id");
					prepayId = (String) prepay_id.get("prepay_id");
					
					//重新签名
					param1.put("appid", "wx10331e9b86cb6027"); 
					param1.put("partnerid", "1406370302"); 
					param1.put("prepayid", prepayId); 
					long second = System.currentTimeMillis()/1000;//（转换成秒）
					String seconds = String.valueOf(second).substring(0, 10);//（截取前10位）
					param1.put("noncestr", StringUtils.generatorNumber(15));
					param1.put("timestamp", seconds); 
					param1.put("package", "Sign=WXPay"); 
					sign = Sign.createSign("UTF-8",param1);  
					param1.put("sign", sign);
				}
				
				//插入订单信息
				who = new WechatOrderInfo();
				who.setUserid(mId.intValue());
				who.setTotalamount(pay_amount);
				who.setBody(list.get(0).getPayName());
				who.setOuttradeno(out_trade_no);
				who.setTimestamp(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
				who.setCreateip(ip);
				who.setPrepayid(prepayId);
				who.setMonthcount(list.get(0).getGiveSum().intValue());
				int i = wechatOrderInfoMapper.insert(who);
				if(i==1)
				{
					results.put("status", "0");
					results.put("data", param1);
					results.put("outTradeNo", out_trade_no);
				}
			}
		} else {
			results.put("status", "2");
		}
		return results;
	}

}
